#include "Subsystems/BlockBehaviors/SubsystemMatchBlockBehavior.h"
#include "Subsystems/BlockBehaviors/SubsystemFireBlockBehavior.h"

#include "Log.h"
#include "GameSingleton.h"
#include "GameRegistry.hpp"

#include "Components/ComponentMiner.h"
#include "Components/ComponentOnFire.h"
#include "Components/ComponentBody.h"
#include "Components/ComponentPlayer.h"

#include "Player/PlayerData.h"
#include "Game/BodyRaycastResult.hpp"
#include "Blocks/MatchBlock.h"



namespace PocketSurvival
{
    SubsystemMatchBlockBehavior::SubsystemMatchBlockBehavior()
    {
        m_handleBlocks.push_back(MatchBlock::Index());
    }


    bool SubsystemMatchBlockBehavior::onUse(const Ray3 &ray, ComponentMiner *componentMiner)
    {
        RaycastData raycastData = componentMiner->raycast(ray, RaycastMode::Digging);
        if(raycastData.terrainRaycastResult != nullptr)
        {
            if(fireBlockBehavior->setCellOnFire(raycastData.terrainRaycastResult->cellFace.point, 1.0f, componentMiner))
            {
                componentMiner->removeActiveTool(1);
                return true;
            }
        }
        else if(raycastData.bodyRaycastResult != nullptr)
        {
            ComponentOnFire **componentOnFirePtr = GameSingleton::gameRegistry->try_get<ComponentOnFire*>(raycastData.bodyRaycastResult->componentBody->entity);
            if(componentOnFirePtr != nullptr)
            {
                ComponentOnFire *onFire = *componentOnFirePtr;
                if(componentMiner->componentPlayer->playerData->gameMode < GameMode::Challenging || GameSingleton::gameRandom->getBool(0.33f))
                {
                    onFire->setOnFile(componentMiner->entity, GameSingleton::gameRandom->getFloat(6.0f, 8.0f));
                }
                componentMiner->removeActiveTool(1);
                return true;
            }
        }
        return false;
    }

    void SubsystemMatchBlockBehavior::load(const nlohmann::json &json)
    {
        fireBlockBehavior = GameSingleton::singletonPtr->getSingleton<SubsystemFireBlockBehavior>();
    }


    static const std::string subsystemName = "MatchBlockBehavior";
    const std::string& SubsystemMatchBlockBehavior::getName() const
    {
        return subsystemName;
    }
}